package com.ihr360.job.core.job.builder;

import com.ihr360.job.core.Job;
import com.ihr360.job.core.Step;
import com.ihr360.job.core.job.SimpleJob;

import java.util.ArrayList;
import java.util.List;

public class SimpleJobBuilder extends JobBuilderHelper<SimpleJobBuilder> {

    private List<Step> steps = new ArrayList<Step>();


    /**
     * Create a new builder initialized with any properties in the parent. The parent is copied, so it can be re-used.
     *
     * @param parent the parent to use
     */
    public SimpleJobBuilder(JobBuilderHelper<?> parent) {
        super(parent);
    }

    public Job build() {

        SimpleJob job = new SimpleJob(getName());
        super.enhance(job);
        job.setSteps(steps);
        try {
            job.afterPropertiesSet();
        }
        catch (Exception e) {
            throw new JobBuilderException(e);
        }
        return job;
    }


    /**
     * Start the job with this step.
     *
     * @param step a step to start with
     * @return this for fluent chaining
     */
    public SimpleJobBuilder start(Step step) {
        if (steps.isEmpty()) {
            steps.add(step);
        }
        else {
            steps.set(0, step);
        }
        return this;
    }

    /**
     * Continue or end a job with this step if the previous step was successful.
     *
     * @param step a step to execute next
     * @return this for fluent chaining
     */
    public SimpleJobBuilder next(Step step) {
        steps.add(step);
        return this;
    }
}